package com.hxexp.weixin.hpe.api.arrivestations.impl;

import java.io.IOException;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.type.TypeReference;
import com.hxexp.weixin.common.config.HpeApiURLConfig;
import com.hxexp.weixin.common.exception.APIException;
import com.hxexp.weixin.common.httpclient.Json2ObjectHandler;
import com.hxexp.weixin.common.json.JsonUtil;
import com.hxexp.weixin.hpe.api.arrivestations.ArriveStationsAPI;
import com.hxexp.weixin.hpe.api.arrivestations.model.ArriveStationsParamBean;
import com.hxexp.weixin.hpe.api.arrivestations.model.ArriveStationsResultBean;

/**
 * HPE到达站列表接口实现类
 *
 * @author wang.bin
 * @author li.jiang
 */
@Component
public final class ArriveStationsAPIImpl implements ArriveStationsAPI {

    private final CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(new PoolingHttpClientConnectionManager()).build();
    private static final String URI = "station/arrivestations";
    @Autowired
    private HpeApiURLConfig config;

    @Override
    @Cacheable(value = "arriveStationsCache", key = "#paramBean.toString()")
    public ArriveStationsResultBean getArriveStations(ArriveStationsParamBean paramBean)
            throws APIException {
        HttpPost post = new HttpPost(config.getURL(URI));
        String postData = JsonUtil.writeObject2JsonString(paramBean);

        // 设置请求体数据
        StringEntity entity = new StringEntity(postData, ContentType.create("application/json", "utf-8"));
        post.setEntity(entity);

        TypeReference<ArriveStationsResultBean> typeReference = new TypeReference<ArriveStationsResultBean>() {
        };
        try {
            return httpclient.execute(post, new Json2ObjectHandler<ArriveStationsResultBean>(typeReference));
        } catch (IOException e) {
            throw new APIException(e);
        }
    }

}
